import Taro from '@tarojs/taro'
import React, { useCallback, useMemo } from 'react'
import { Image, View } from '@tarojs/components'
import Images from '@ASSET/Images'
import { Analytic_Type } from '@CONSTANTS/analytic'
import './index.scss'

const Index = ({
  data, onDelete, onUpload, maxLength, sizeType = ['compressed', 'original'], showTop = false, page = ''
}) => {
  const onDeleteFunc = useCallback(index => {
    onDelete?.(index)
  }, [onDelete])
  const onUploadFunc = useCallback(() => {
    const len = data?.length || 0
    page && Taro.tracker.trackEvent(Analytic_Type.tap_upload_file.eventId, { Page: page })
    Taro.chooseImage({
      count: maxLength - len,
      sizeType,
      sourceType: ['album', 'camera'],
      success: res => {
        const { tempFiles } = res
        if (!tempFiles || !tempFiles.length) return
        const selectLen = tempFiles.length
        if (len + selectLen > maxLength) {
          Taro.showToast({
            title: `最多上传${maxLength}张`,
            icon: 'none'
          })
        }
        onUpload?.(tempFiles.slice(0, maxLength - len))
      }
    })
  }, [data?.length, maxLength, onUpload, page, sizeType])
  const onPreviewImage = useCallback(index => {
    if (!data) return
    Taro.previewImage({
      current: data[index]?.path,
      urls: data.map(item => item.path)
    })
  }, [data])
  const showUpload = data?.length < maxLength

  const BtnCom = useMemo(() => (
    <View className="upload-image-item">
      <View className="upload-image-add" onClick={onUploadFunc}>
        <Image src={Images.greyAdd} className="upload-image-icon" mode="aspectFill" />
      </View>
    </View>
  ), [onUploadFunc])
  return (
    <View className="upload-image-container">
      {showTop && showUpload ? BtnCom : null}
      {Array.isArray(data) && data.map(({ path, fullPath }, index) => (
        <View className="upload-image-item" key={path || `${index}`}>
          <Image
            src={fullPath || path}
            mode="aspectFill"
            className="upload-image-item-image"
            onClick={() => onPreviewImage(index)}
          />
          <Image src={Images.delete} className="upload-image-delete" onClick={() => onDeleteFunc(index)} />
        </View>
      ))}
      {!showTop && showUpload ? BtnCom : null}
    </View>
  )
}

Index.defaultProps = {
  data: [],
  maxLength: 9
}
export default Index
